<template>
  <div>
<van-pull-refresh class="article-list-container" v-model="isLoading" :success-text="refreshInfo" @refresh="onRefresh">

<van-list v-model="loading" :finished="finished" finished-text="没有更多了" :error.sync="error" error-text="请求失败，点击重新加载"
  @load="onLoad" success-duration="1500">
  <van-cell v-for="(item, index) in list" :key="index" >
    <ArticleItem :article="item" />
  </van-cell>
</van-list>

</van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesApi } from '@/api/index.js'
import ArticleItem from './article-item'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false, // 控制列表加载失败的提示状态
      isLoading: false, // 下拉状态
      refreshInfo: '刷新成功'
    }
  },
  methods: {
    // 1. 请求数据
    async onLoad () {
      console.log(this.channel.id)
      try {
        const { data: res } = await getArticlesApi({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })
        console.log(res)
        // 2. 把数据添加到list数组中
        this.list.push(...res.data.results)
        // 3. 设置本次加载中 loading 状态结束
        this.loading = false
        // 4. 判断所有数据是否加载完
        if (res.data.results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = res.data.pre_timestamp
        } else {
          // 没有数据 设置加载结束 不触发上拉加载更多
          this.finished = true // 全部加载完成
        }
      } catch (e) {
        // 展示错误提示状态
        this.error = true
        this.loading = false // 报错则加载结束
        console.log(e)
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data: res } = await getArticlesApi({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // 2. 把数据添加到list数组中
        this.list.unshift(...res.data.results)
        // 3. 设置本次加载中 loading 状态结束
        this.isLoading = false // 刷新完成
        this.refreshInfo = `刷新成功，更新了${res.data.results.length}条数据`
      } catch (e) {
        this.isLoading = false // 刷新完成
        // 展示错误提示状态
        this.refreshInfo = '刷新失败'
        console.log(e)
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list-container {
  overflow-y: auto;
  height: 80vh;
}
</style>
